<?php

new SET_Type();

class SET_Type
{

	public function __construct()
	{
		global $restype;
		if (isset($_GET['action']))
		{
			$action = $_GET['action'];
		}
		elseif (isset($_POST['edit']))
		{
			$this->editAction();
			exit();
		}
		elseif (isset($_GET['remove']))
		{
			$this->removeAction();
			exit();
		}
		elseif (isset($_POST['action']))
		{
			$this->addAction();
			exit();
		}
		require(PrintEot('header'));
		require(PrintEot('set_type'));
		adminbottom();
	}

	protected function addAction()
	{
		global $db, $restype;
		$typename = Char_cv($_POST['typename']);
		$typeext = $_POST['typeext'];
		if (empty($typename) || empty($typeext))
		{
			Showmsg('请填入完整的扩展名和类型名称');
		}

		if (!preg_match("/^[a-zA-Z0-9,]+$/", $typeext))
		{
			Showmsg('您输入的扩展名不符合要求，文件扩展名不能包含特殊字符。');
		}
		$extArray = explode(',', $typeext);

		$ext = array();
		foreach ($restype as $r)
		{
			$ext = array_merge($ext, $r['typeext']);
		}

		foreach ($extArray as $e)
		{
			if (in_array($e, $ext)) Showmsg($e . '这个扩展名已经存在。');
		}
		$typeext = strtolower($typeext);
		$db->query("INSERT cms_restype SET typename='$typename',typeext='$typeext'");
		require_once(R_P . 'require/class_cache.php');
		Cache::writeCache('config');
		adminmsg('资源类型添加成功');
	}

	protected function editAction()
	{
		global $db;
		$typeName = array();
		foreach ($_POST['typename'] as $name)
		{
			$name = trim($name);
			if (in_array($name, $typeName)) Showmsg('类型名重复');
			$typeName[] = $name;
		}
		$typeExt = array();
		foreach ($_POST['typeext'] as $ext)
		{
			$ext = trim($ext);
			if (!preg_match("/^[a-zA-Z0-9,]+$/", $ext))
			{
				Showmsg('您输入的扩展名' . $ext . '不符合要求，文件扩展名不能包含特殊字符。');
			}
			$exts = explode(',', $ext);
			foreach ($exts as $e)
			{
				if (empty($e)) continue;
				if (in_array($e, $typeExt)) Showmsg($e . '这个扩展名已经存在。');
			}
			$typeExt = array_merge($typeExt, $exts);
		}
		foreach ($_POST['typeext'] as $key => $val)
		{
			$ext = $val;
			$name = $_POST['typename'][$key];
			$ext = strtolower($ext);
			$sql = "UPDATE cms_restype SET typename='$name',typeext='$ext' WHERE typeid='$key'";
			$db->query($sql);
		}
		require_once(R_P . 'require/class_cache.php');
		Cache::writeCache('config');
		adminmsg('资源类型更新成功');

	}

	protected function removeAction()
	{
		$typeId = intval($_GET['remove']);
		global $db;
		if (in_array($typeId, array(1, 2, 3))) {
			Showmsg('对不起，图片、视频、音频三种类型为系统内置，无法删除');
		}
		$db->query("DELETE FROM cms_restype WHERE typeid='$typeId'");
		require_once(R_P . 'require/class_cache.php');
		Cache::writeCache('config');
		adminmsg('资源类型删除成功');
	}

}
?>